<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface Device {
  id: string;
  name: string;
  icon: string;
  status: 'offline' | 'online';
  lastConnectTime?: string;
}

interface SyncedImage {
  id: string;
  name: string;
  url: string;
  syncTime: string;
  type: 'sync';
  selected: boolean;
}

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'success',images: SyncedImage[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const isSyncing = ref(false);
const syncProgress = ref(0);
const syncStatus = ref<'active' | 'exception' | 'success'>('active');
const syncColor = ref('#1890ff');
const syncMessage = ref('');
const syncedImages = ref<SyncedImage[]>([]);

// 设备数据
const devices = ref<Device[]>([
  {
    id: '1',
    name: 'DR-X光机',
    icon: '📷',
    status: 'online',
    lastConnectTime: dayjs()
      .subtract(5, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
  {
    id: '2',
    name: 'CR-X光机',
    icon: '📸',
    status: 'offline',
  },
  {
    id: '3',
    name: '移动X光机',
    icon: '📱',
    status: 'online',
    lastConnectTime: dayjs()
      .subtract(2, 'minute')
      .format('YYYY-MM-DD HH:mm:ss'),
  },
]);

// 计算属性
const hasOnlineDevice = computed(() => {
  return devices.value.some((device) => device.status === 'online');
});

const selectedImages = computed(() => {
  return syncedImages.value.filter((image) => image.selected);
});

// 方法
const connectDevice = (device: Device) => {
  if (device.status === 'offline') {
    message.warning('设备离线，无法连接');
    return;
  }

  device.lastConnectTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  message.success(`已连接到${device.name}`);
};

const startSync = () => {
  if (!hasOnlineDevice.value) {
    message.warning('没有可用的在线设备');
    return;
  }

  isSyncing.value = true;
  syncProgress.value = 0;
  syncStatus.value = 'active';
  syncColor.value = '#1890ff';
  syncMessage.value = '正在连接设备...';

  // 模拟同步过程
  const interval = setInterval(() => {
    syncProgress.value += Math.random() * 20;

    if (syncProgress.value >= 100) {
      syncProgress.value = 100;
      syncStatus.value = 'success';
      syncColor.value = '#52c41a';
      syncMessage.value = '同步完成';

      // 生成同步的图片
      generateSyncedImages();

      clearInterval(interval);
      setTimeout(() => {
        isSyncing.value = false;
      }, 1000);
    } else {
      const messages = [
        '正在扫描设备...',
        '发现新图片...',
        '正在下载图片...',
        '正在处理图片...',
        '正在验证图片...',
      ];
      const randomMessage =
        messages[Math.floor(Math.random() * messages.length)];
      syncMessage.value = randomMessage;
    }
  }, 1000);
};

const generateSyncedImages = () => {
  const imageTypes = [
    '胸部正位',
    '胸部侧位',
    '腹部正位',
    '脊柱侧位',
    '四肢正位',
  ];
  const newImages: SyncedImage[] = [];newImagesnewImages

  for (let i = 0; i < Math.floor(Math.random() * 3) + 1; i++) {
    const imageType = imageTypes[Math.floor(Math.random() * imageTypes.length)];
    newImages.push({
      id: Date.now().toString() + i,
      name: `${imageType}片_${dayjs().format('YYYYMMDD_HHmmss')}`,
      url: `https://via.placeholder.com/300x400/87CEEB/000000?text=${imageType}`,
      syncTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      type: 'sync',
      selected: true,
    });
  }

  syncedImages.value = newImages;
};

const handleImageSelect = () => {
  // 图片选择状态已通过 v-model 自动更新
};

const handleConfirm = () => {
  if (selectedImages.value.length === 0) {
    message.warning('请选择要同步的图片');
    return;
  }

  emit('success', selectedImages.value);
  handleCancel();
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  isSyncing.value = false;
  syncProgress.value = 0;
  syncedImages.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置状态
      isSyncing.value = false;
      syncProgress.value = 0;
      syncedImages.value = [];
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="从设备同步X光片"
    width="800px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="device-sync-modal">
      <!-- 设备状态 -->
      <div class="device-status">
        <h4>设备状态</h4>
        <div class="device-grid">
          <div
            v-for="device in devices"
            :key="device.id"
            class="device-card"
            :class="{
              online: device.status === 'online',
              offline: device.status === 'offline',
            }"
          >
            <div class="device-icon">{{ device.icon }}</div>
            <div class="device-info">
              <div class="device-name">{{ device.name }}</div>
              <div class="device-status">
                <a-tag :color="device.status === 'online' ? 'green' : 'red'">
                  {{ device.status === 'online' ? '在线' : '离线' }}
                </a-tag>
              </div>
            </div>
            <div class="device-actions">
              <a-button
                type="primary"
                size="small"
                @click="connectDevice(device)"
                :disabled="device.status === 'offline'"
              >
                连接
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 同步进度 -->
      <div v-if="isSyncing" class="sync-progress">
        <h4>同步进度</h4>
        <div class="progress-content">
          <a-progress
            :percent="syncProgress"
            :status="syncStatus"
            :stroke-color="syncColor"
          />
          <div class="progress-text">{{ syncMessage }}</div>
        </div>
      </div>

      <!-- 同步结果 -->
      <div v-if="syncedImages.length > 0" class="sync-results">
        <h4>同步结果</h4>
        <div class="results-grid">
          <div
            v-for="(image, index) in syncedImages"
            :key="index"
            class="result-item"
          >
            <div class="result-container">
              <img :src="image.url" :alt="image.name" />
              <div class="result-overlay">
                <a-checkbox
                  v-model:checked="image.selected"
                  @change="handleImageSelect"
                />
              </div>
            </div>
            <div class="result-info">
              <div class="result-name">{{ image.name }}</div>
              <div class="result-time">{{ image.syncTime }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          v-if="!isSyncing"
          type="primary"
          @click="startSync"
          :disabled="!hasOnlineDevice"
        >
          开始同步
        </a-button>
        <a-button
          v-if="syncedImages.length > 0"
          type="primary"
          @click="handleConfirm"
          :disabled="selectedImages.length === 0"
        >
          确认同步 ({{ selectedImages.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.device-sync-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.device-status,
.sync-progress,
.sync-results {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.device-status h4,
.sync-progress h4,
.sync-results h4 {
  margin: 0 0 16px;
  font-size: 14px;
  color: #333;
}

.device-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.device-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: all 0.3s;
}

.device-card.online {
  background: #f6ffed;
  border-color: #52c41a;
}

.device-card.offline {
  background: #fff2f0;
  border-color: #ff4d4f;
}

.device-icon {
  margin-right: 12px;
  font-size: 24px;
}

.device-info {
  flex: 1;
}

.device-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.device-actions {
  margin-left: 8px;
}

.progress-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.progress-text {
  font-size: 14px;
  color: #666;
  text-align: center;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
}

.result-item {
  overflow: hidden;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.result-container {
  position: relative;
  height: 120px;
  overflow: hidden;
}

.result-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.result-overlay {
  position: absolute;
  top: 4px;
  left: 4px;
  padding: 2px;
  background: rgb(255 255 255 / 90%);
  border-radius: 4px;
}

.result-info {
  padding: 8px;
}

.result-name {
  margin-bottom: 4px;
  font-size: 12px;
  color: #333;
}

.result-time {
  font-size: 10px;
  color: #999;
}

.modal-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}
</style>
